import Ember from 'ember';
import DS from 'ember-data';

var inflector = Ember.Inflector.inflector;

inflector.irregular('person', 'people');
inflector.uncountable('advice');

export default DS.RESTAdapter.extend({
  namespace: 'api/v1',
  headers: {},
  buildURL: function(modelName, id, snapshot, requestType, query) {
    // console.log(requestType);
    // console.log(query);
    // console.log(id);
    // console.log(snapshot);
    var metaq = {};
    if (query) {
      Object.keys(query).forEach((it) => {
        if (it.indexOf('__') === 0) {
          metaq[it] = query[it];
          delete query[it];
        }
      });
    }

    var url = this._super(modelName, id, snapshot, requestType, query);

    if (requestType === "updateRecord") {
      url = url + "/update";
    }
    if ((requestType === "query" || requestType === "queryRecord") && metaq.__restsearch) {
      var qmarkerindex = url.indexOf('?');
      var s1, s2;
      if (qmarkerindex === -1) {
        s1 = url;
        s2 = "";
      } else {
        s1 = url.substring(0, qmarkerindex);
        s2 = url.substring(qmarkerindex);
      }
      url = s1 + "/search/" + metaq.__restsearch + s2;
    }
    // console.log(url);
    return url;
  },
  ajaxError: function(jqXHR) {
    var error = this._super(jqXHR);
    // console.log(jqXHR);
    if (jqXHR) {
      if (jqXHR.status === 422) {
        var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
        return new DS.InvalidError(jsonErrors);
      } else if (jqXHR.status === 201) {
        return {
          errors: {
            noerror: true
          }
        };
      } else {
        return error;
      }
    } else {
      return error;
    }
    if (jqXHR && jqXHR.status === 422) {} else {
      return error;
    }
  }
});
